<template>
  <div class="re-password hiddenScroll">
    <!-- 输入账号 -->
    <div v-if="step == 0" class="re-password-box">
      <div class="title">找回密码</div>
      <div class="flex-box">
        <TextInput
          :options="{ text: '账号', placeholder: '请输入需要找回的账号' }"
          @change="account.id = $event"
        ></TextInput>
      </div>
      <div class="button">
        <el-button type="primary" icon="Right" circle @click="findAccount" />
      </div>
    </div>
    <!-- 输入密保问题 -->
    <div v-if="step == 1" class="re-password-box">
      <div class="title">回答问题</div>
      <div class="flex-box">
        <TextInput
          :options="{ text: `${account.question1}`, placeholder: '请输入问题1的答案' }"
          @change="answer($event, 1)"
        ></TextInput>
        <TextInput
          :options="{ text: `${account.question2}`, placeholder: '请输入问题2的答案' }"
          @change="answer($event, 2)"
        ></TextInput>
      </div>
      <div class="button">
        <el-button type="primary" icon="Right" circle @click="checkAnswer" />
      </div>
    </div>
    <!-- 输入新密码 -->
    <div v-if="step == 2" class="re-password-box">
      <div class="title">输入新密码</div>
      <div class="flex-box">
        <el-form
          label-width="auto"
          :model="account"
          style="width: 350px"
          ref="formPassword"
          :rules="rules"
        >
          <el-form-item label="新密码" prop="password">
            <el-input
              v-model="account.password"
              type="password"
              show-password
              placeholder="请输入你的新密码"
            />
          </el-form-item>
          <el-form-item label="确认密码" prop="passwordSure">
            <el-input
              v-model="account.passwordSure"
              type="password"
              show-password
              placeholder="请确认你的新密码"
            />
          </el-form-item>
        </el-form>
      </div>
      <div class="button">
        <el-button type="primary" icon="Right" circle @click="commitChange" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { updatePassword } from '@/api/login'
import { getQuestion } from '@/api/user'
import { useRouter } from 'vue-router'
import { ref } from 'vue'

// 定义路由器
const router = useRouter()

const rules = {
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的非空字符',
      trigger: 'blur',
    },
  ],
  passwordSure: [
    { required: true, message: '请重复输入密码', trigger: 'blur' },
    {
      pattern: /^\S{6,15}$/,
      message: '密码必须是6-15位的非空字符',
      trigger: 'blur',
    },
    {
      validator: (rule, value, callback) => {
        if (value !== account.value.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
}

const account = ref({
  id: '',
  question1: '',
  answer1: '',
  question2: '',
  answer2: '',
  password: '',
  passwordSure: '',
})

const answerText = ref({
  answer1: '',
  answer2: '',
})

const step = ref(0)

// 密码表单
const formPassword = ref(null)

// 输入问题答案
const answer = (val, i) => {
  answerText.value[`answer${i}`] = val
}

// 寻找账号
const findAccount = async () => {
  const res = (await getQuestion(account.value.id)).data
  if (!res.success) {
    ElNotification({
      title: '错误',
      message: '账号不存在',
      type: 'error',
    })
    return
  }
  const answers = [] // 存储问题
  Object.entries(res.data.questions).forEach(([question, answer]) => {
    answers.push(question)
  })
  // 将问题答案赋值
  for (let i = 0; i < answers.length; i++) {
    account.value[`question${i + 1}`] = answers[i]
    account.value[`answer${i + 1}`] = res.data.questions[answers[i]]
  }
  step.value = 1
}

// 检查答案
const checkAnswer = () => {
  if (
    account.value.answer1 != answerText.value.answer1 ||
    account.value.answer2 != answerText.value.answer2
  ) {
    ElNotification({
      title: '错误',
      message: '答案错误',
      type: 'error',
    })
    return
  }
  step.value = 2
}

// 提交修改
const commitChange = async () => {
  await formPassword.value.validate()
  const res = (await updatePassword(account.value)).data
  if (!res.success) {
    ElNotification({
      title: '错误',
      message: '修改失败，请稍后重试',
      type: 'error',
    })
    return
  }
  ElNotification({
    title: '修改成功',
    message: '你已成功修改密码',
    type: 'success',
  })
  router.replace({ path: '/' })
}
</script>

<style scoped less="scss">
.re-password {
  background-color: #f7fcf8;
  height: 1100px;
  /* 防止子元素margin越级 */
  border-top: 1px solid transparent;

  .re-password-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    /* 设置宽高 */
    width: 600px;
    height: 400px;
    /* 上下外边距200px，左右居中 */
    margin: 200px auto;
    /* 设置圆角 */
    border-radius: 20px;
    /* 设置背景 */
    background: no-repeat url(../../assets/login-bg.png) center;
    /* 设置阴影 */
    box-shadow: -3px 3px 10px 2px #dfe5fc;

    .title {
      font-size: 1.5rem;
      letter-spacing: 0.1em;
    }

    .flex-box {
      width: 100%;
      min-height: 200px;
      display: flex;
      /* 修改主轴方向 */
      flex-direction: column;
      align-items: center;
      justify-content: center;
      /* 使弹性布局间隔30px */
      gap: 30px;
    }
  }
}
</style>
